package com.cy.law.utils;

import com.cy.law.db.entity.Human;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@Data
@Slf4j
public class SessionUtil {
    private static final String SESSION_NAME = "human";

    public static Human getHumanSession(HttpServletRequest request) {
        return (Human) request.getSession().getAttribute(SESSION_NAME);
    }

    public static Integer getHumanId(HttpServletRequest request) {
        Human human = getHumanSession(request);
        return human == null ? null : human.getHumanId();
    }

    public static Integer getUnitId(HttpServletRequest request) {
        Human human = getHumanSession(request);
        return human == null ? null : human.getUnitId();
    }


    public static boolean login(HttpServletRequest request, Human human) {
        try {
            request.getSession().setAttribute(SESSION_NAME, human);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public static boolean logout(HttpServletRequest request) {
        try {
            request.getSession().removeAttribute(SESSION_NAME);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }


    public static boolean sessionInvalid(HttpServletRequest request) {
        try {
            Human human = getHumanSession(request);
            return human != null;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 获取客户端IP地址
     *
     * @param request
     * @return
     */
    public static String getIPAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
